package com.wangzhenyu.common.net

import com.blankj.utilcode.util.AppUtils
import com.wangzhenyu.common.design.MySingleton
import com.wangzhenyu.common.netcore.networking.http.core.HiConverterFactory
import com.wangzhenyu.common.netcore.networking.http.core.PassThroughExecutor
import com.wangzhenyu.common.util.log.LogUtil
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.net.URLDecoder
import java.util.concurrent.TimeUnit

//其实就是在生成RetrofitUtil实例时给retrofit赋值
class RetrofitUtil private constructor() {

    companion object : MySingleton<String, RetrofitUtil>() {

        private const val TAG = "RetrofitUtil"

        override val creator: (String) -> RetrofitUtil
            get() = {
                retrofit = initRetrofit(baseUrl)
                retrofitOther = initRetrofit(baseOtherUrl)
                RetrofitUtil()
            }

        private const val DEFAULT_TIMEOUT = 90L

        //基础的API
        //这里用一下Gitee的API
        //https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoStargazers?ex=no
        var baseUrl = ""

        var baseOtherUrl = ""

        @Volatile
        private var retrofit: Retrofit? = null

        @Volatile
        private var retrofitOther: Retrofit? = null

        @Volatile
        var interceptor: Interceptor? = null

        @Volatile
        var okHttpClient: OkHttpClient? = null
            private set

        private fun initOkHttpClient(): OkHttpClient {

            val logging = HttpLoggingInterceptor { message ->
                try {
                    val text = URLDecoder.decode(message, "utf-8")
                    LogUtil.d(TAG, text)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            logging.setLevel(HttpLoggingInterceptor.Level.BODY)

            val httpClientBuilder = OkHttpClient.Builder()
            httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            httpClientBuilder.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)

            interceptor?.let { httpClientBuilder.addInterceptor(it) }
            if (AppUtils.isAppDebug()) {
                httpClientBuilder.addInterceptor(logging)
            }
            return httpClientBuilder.build()

        }

        private fun initRetrofit(url: String): Retrofit {
            val client = initOkHttpClient()
            val mRetrofit = Retrofit.Builder()
                .baseUrl(url)
                //在nextRequestBodyConverter(...) 方法 和 nextResponseBodyConvert(...)方法在,可以看到:
                //按照retrofit的逻辑，是从前往后进行匹配，如果匹配上，就忽略后面的，直接使用。
                .addConverterFactory(HiConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .callbackExecutor(PassThroughExecutor())
                .client(client)
                .build()
            okHttpClient = client
            return mRetrofit
        }

    }

    //我们需要RetrofitUtil初始化后才获得retrofit
    fun getRetrofit() = retrofit!!

    fun getOtherRetrofit() = retrofitOther!!

}